/* eslint-disable */
<template>
  <!-- 课程管理页面容器 -->
  <div class="courses-container">
    <!-- 页面标题和工具栏 -->
    <div class="page-header">
      <h3>课程管理</h3>
      <div class="filter-container">
        <el-input
          v-model="searchQuery"
          placeholder="搜索课程"
          class="filter-item"
          @keyup.enter.native="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
        
        <el-button
          class="filter-item"
          style="margin-left: 10px;"
          type="primary"
          icon="el-icon-plus"
          @click="handleAddCourse"
        >
          添加课程
        </el-button>
      </div>
    </div>

    <!-- 课程列表表格 -->
    <el-table
      v-loading="loading"
      :data="displayCourses"
      style="width: 100%; margin-top: 15px;"
      border
    >
      <el-table-column prop="courseId" label="课程编码" align="center" width="120"></el-table-column>
      <el-table-column prop="courseName" label="课程名称" align="center"></el-table-column>
      <el-table-column prop="description" label="课程描述" align="center" show-overflow-tooltip></el-table-column>
      
      <el-table-column label="操作" align="center" width="200">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEditCourse(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDeleteCourse(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑课程对话框 -->
    <el-dialog 
      :title="dialogStatus === 'create' ? '添加课程' : '编辑课程'" 
      :visible.sync="dialogVisible"
      width="500px"
    >
      <el-form 
        ref="courseForm" 
        :model="courseForm" 
        :rules="courseRules" 
        label-position="right" 
        label-width="100px"
      >
        <el-form-item label="课程编码" prop="courseId">
          <el-input 
            v-model="courseForm.courseId" 
            placeholder="请输入课程编码"
            :disabled="dialogStatus === 'update'"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="courseForm.courseName" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        
        <el-form-item label="课程描述" prop="description">
          <el-input 
            v-model="courseForm.description" 
            type="textarea" 
            :rows="4"
            placeholder="请输入课程描述"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createCourse() : updateCourse()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { 
  getAllCourses, 
  addCourse, 
  updateCourse, 
  deleteCourse,
  searchCourses
} from '@/api/admin'

export default {
  name: 'CourseManagement',
  data() {
    return {
      courses: [],
      loading: true,
      searchQuery: '',
      dialogVisible: false,
      dialogStatus: 'create',
      courseForm: {
        courseId: '',
        courseName: '',
        description: ''
      },
      courseRules: {
        courseId: [
          { required: true, message: '请输入课程编码', trigger: 'blur' },
          { pattern: /^[A-Za-z0-9-_]+$/, message: '课程编码只能包含字母、数字、短横线和下划线', trigger: 'blur' }
        ],
        courseName: [
          { required: true, message: '请输入课程名称', trigger: 'blur' }
        ],
        description: [
          { required: false, message: '请输入课程描述', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    displayCourses() {
      if (!this.searchQuery) {
        return this.courses;
      }
      const query = this.searchQuery.toLowerCase();
      return this.courses.filter(course => {
        return course.courseId.toLowerCase().includes(query) ||
               course.courseName.toLowerCase().includes(query) ||
               (course.description && course.description.toLowerCase().includes(query));
      });
    }
  },
  created() {
    this.fetchCourses();
  },
  methods: {
    async fetchCourses() {
      this.loading = true;
      try {
        const response = await getAllCourses();
        if (response.code === 200) {
          this.courses = response.data;
        } else {
          this.$message.error('获取课程列表失败：' + response.msg);
        }
      } catch (error) {
        console.error('获取课程列表失败', error);
        this.$message.error('获取课程列表失败：' + error.message);
      } finally {
        this.loading = false;
      }
    },
    
    handleSearch() {
      if (this.searchQuery.trim()) {
        this.loading = true;
        searchCourses(this.searchQuery.trim())
          .then(response => {
            if (response.code === 200) {
              this.courses = response.data;
            } else {
              this.$message.error('搜索课程失败：' + response.msg);
            }
          })
          .catch(error => {
            console.error('搜索课程失败', error);
            this.$message.error('搜索课程失败：' + error.message);
          })
          .finally(() => {
            this.loading = false;
          });
      } else {
        this.fetchCourses();
      }
    },
    
    handleAddCourse() {
      this.dialogStatus = 'create';
      this.resetCourseForm();
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.courseForm.clearValidate();
      });
    },
    
    handleEditCourse(row) {
      this.dialogStatus = 'update';
      this.courseForm = Object.assign({}, row);
      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs.courseForm.clearValidate();
      });
    },
    
    handleDeleteCourse(row) {
      this.$confirm(`确认删除课程 ${row.courseName}?`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteCourse(row.courseId)
          .then(response => {
            if (response.code === 200) {
              this.$message.success('删除课程成功');
              this.fetchCourses();
            } else {
              this.$message.error('删除课程失败：' + response.msg);
            }
          })
          .catch(error => {
            console.error('删除课程失败', error);
            this.$message.error('删除课程失败：' + error.message);
          });
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },
    
    resetCourseForm() {
      this.courseForm = {
        courseId: '',
        courseName: '',
        description: ''
      };
    },
    
    createCourse() {
      this.$refs.courseForm.validate(valid => {
        if (valid) {
          const courseData = { ...this.courseForm };
          addCourse(courseData)
            .then(response => {
              if (response.code === 200) {
                this.$message.success('添加课程成功');
                this.dialogVisible = false;
                this.fetchCourses();
              } else {
                this.$message.error('添加课程失败：' + response.msg);
              }
            })
            .catch(error => {
              console.error('添加课程失败', error);
              this.$message.error('添加课程失败：' + error.message);
            });
        } else {
          return false;
        }
      });
    },
    
    updateCourse() {
      this.$refs.courseForm.validate(valid => {
        if (valid) {
          const courseData = { ...this.courseForm };
          const courseId = courseData.courseId;
          updateCourse(courseId, courseData)
            .then(response => {
              if (response.code === 200) {
                this.$message.success('更新课程成功');
                this.dialogVisible = false;
                this.fetchCourses();
              } else {
                this.$message.error('更新课程失败：' + response.msg);
              }
            })
            .catch(error => {
              console.error('更新课程失败', error);
              this.$message.error('更新课程失败：' + error.message);
            });
        } else {
          return false;
        }
      });
    }
  }
}
</script>

<style scoped>
/* 课程管理页面容器样式：设置内边距 */
.courses-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
}

/* 页面标题和工具栏样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

/* 页面标题样式 */
.page-header h3 {
  margin: 0;
}

/* 过滤器容器样式 */
.filter-container {
  display: flex;
  align-items: center;
}

/* 过滤器项目样式 */
.filter-item {
  width: 200px;
  margin-right: 10px;
}

/* 表格样式：设置上边距 */
.el-table {
  margin-top: 15px;
}

/* 对话框底部按钮样式 */
.dialog-footer {
  text-align: right;
}
</style> 
